﻿using AutoMapper;
using Basic.Traceability.Domain.DeepProcessing;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.DeepProcessing.DeepProcessingProductionTeam;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.DeepProcessing.DeepProcessingProductionTeam
{
    public class CreateDeepProcessingProductionTeamHandler : IRequestHandler<CreateDeepProcessingProductionTeamCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingProductionTeamModel> _deepProcessingProductionTeamRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateDeepProcessingProductionTeamHandler> _logger;

        public CreateDeepProcessingProductionTeamHandler(IBaseRepository<DeepProcessingProductionTeamModel> deepProcessingProductionTeamRepository, IMapper mapper, ILogger<CreateDeepProcessingProductionTeamHandler> logger)
        {
            _deepProcessingProductionTeamRepository = deepProcessingProductionTeamRepository;
            _mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 创建生产团队
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateDeepProcessingProductionTeamCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = _mapper.Map<DeepProcessingProductionTeamModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = _deepProcessingProductionTeamRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加生产团队成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                _logger.LogInformation("创建成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "添加生产团队失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                _logger.LogError("创建失败");
                return Task.FromResult(res);
            }
            }

        }
    }
}
